package com.hdw.auth.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hdw.auth.api.CoreAuthorizationService;
import com.hdw.auth.api.SysFucaService;
import com.hdw.auth.api.TagService;
import com.hdw.auth.bean.model.SysFuca;
import com.hdw.auth.bean.model.SysTag;
import com.hdw.auth.bean.vo.LayMsg;
import com.hdw.auth.bean.vo.Msg;
import com.hdw.auth.utils.AuthUtil;
import com.hdw.auth.utils.Ognlutis;
import com.hdw.common.base.BaseResult;
import com.hdw.common.constant.CommonResultConstant;
import com.hdw.common.util.TreeUtil;
import com.hdw.common.vo.LayTreeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author GuoPeng
 * @Title: TagController
 * @Description: 标签控制器
 * @date 2019/5/14 19:06
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@Api(tags = "功能管理")
@RequestMapping("/permission")
public class TagController {


    @Resource
    private TagService tagService;

    @Resource
    private CoreAuthorizationService coreAuthorizationService;

    @Autowired
    SysFucaService sysFucaService;


    //为权限添加标签
    @RequestMapping("/RolesSetTag")
    public Msg RolesSetTag(String LoginKey, String data, Integer id){
        if (coreAuthorizationService.autLoginToken_sta(LoginKey)) {
            Gson gson = new Gson();
            Map map=  (Map)gson.fromJson(data, new TypeToken<Map>(){}.getRawType());
            return tagService.PermissionsSetTag(map, id);
        } else {
            return Msg.fail();
        }
    }

    //获取所有标签
    @RequestMapping("/getTagAll")
    @ResponseBody
    public Msg  getRolesAll(String LoginKey,Integer id){
        if (coreAuthorizationService.autLoginToken_sta(LoginKey)) {
            return tagService.SelectAll(id);
        } else {
            return Msg.fail();
        }
    }

    //以下为角色的增删改查
    @PostMapping("/insertTag")
    @ResponseBody
    public Msg  insertTag(@RequestBody SysTag sysTag){
        try {
            return tagService.insertTag(sysTag);
        }catch (Exception e){
            return Msg.fail().add("info", "标签名称已存在！");
        }
    }


    @RequestMapping("/getTagList")
    @ResponseBody
    public LayMsg getRoleslist(String LoginKey, Integer page, Integer limit) {
        if (coreAuthorizationService.autLoginToken_sta(LoginKey)) {
            return tagService.getTagList(page, limit);
        } else {
            return LayMsg.fail();
        }
    }

    @ResponseBody
    @RequestMapping("/updateTag")
    public Msg updateRoles(String LoginKey, String tag) {
        Gson gson = new Gson();
        SysTag  sysTag = (SysTag) gson.fromJson(tag, new TypeToken<SysTag>() {
        }.getRawType());
        Msg msg = coreAuthorizationService.autLoginToken(LoginKey);
        if (msg.getCode() == 100) {
            return tagService.updateTag(sysTag);
        } else {
            return msg;
        }
    }


    @RequestMapping("/delectTag")
    @ResponseBody
    public Msg delectRoles(String LoginKey, String tag) {
        if (coreAuthorizationService.autLoginToken_sta(LoginKey)) {
            Gson gson = new Gson();
            List<Map> maps = (List) gson.fromJson(tag, new TypeToken<List<Map>>() {
            }.getRawType());
            for (int i = 0; i < maps.size(); i++) {
                Integer id = Ognlutis.getNumber("id", maps.get(i)).intValue();
                Msg delectuser = tagService.delectTag(id);
            }
            return Msg.success();
        }
        return Msg.fail();
    }

    @ApiOperation(value="根据用户查询")
    @RequestMapping(value="findTagsByUse", method=RequestMethod.GET)
    public BaseResult findTagsByUse(Integer useId) {
        List<SysTag> tagList = tagService.findByUse(useId);
        List<SysFuca> fucaList = sysFucaService.findByModel(new SysFuca());
        Map<String, LayTreeVO> treeMap = new HashMap<>();
        LayTreeVO tree;
        AuthUtil.fucaToMaptree(treeMap,fucaList);
        for(SysTag tag:tagList) {
            tree = new LayTreeVO();
            tree.setTitle(tag.getDescription());
            tree.setParent(tag.getIdFuca());
            tree.setId("tag_"+tag.getId());
            tree.setData(tag);
            treeMap.put("tag_"+tag.getId(),tree);
        }
        List<LayTreeVO> treeList = TreeUtil.treeHandler(treeMap);
        List<LayTreeVO> newTreeList = new ArrayList<>();
        for(LayTreeVO treeVO:treeList) {
            if(haveTag(treeVO.getChildren())) {
                newTreeList.add(treeVO);
            }
        }
        return new BaseResult(CommonResultConstant.SUCCESS, newTreeList);
    }

    private boolean haveTag(List<LayTreeVO> treeList) {
        if(treeList==null ||treeList.size()<1) {
            return false;
        }
        List<LayTreeVO> children;
        for(LayTreeVO vo:treeList) {
            if(vo.getId().contains("tag_")) {
                return true;
            } else {
                children = vo.getChildren();
                if(children!=null) {
                    haveTag(children);
                } else {
                    continue;
                }
            }
        }
        return false;
    }

}
